import  { defineStore } from  'pinia'
import {store} from "/@/store";
import {RouteRecordName, RouteRecordRaw} from "vue-router";
import {portalRoutes} from "/@/router/portal";
import {ConsoleRoutes} from "/@/router/console";

interface CacheState {
    noCacheComponentNames: RouteRecordName[],
    cacheComponentNames:  RouteRecordName[],
}
//获取缓存的页面
export function getCacheMenuComponentNames() : CacheState{
    function getCacheName(routes : RouteRecordRaw[]):CacheState{
        const cacheComponentNames:RouteRecordName[] = [];
        const noCacheComponentNames:RouteRecordName[] = [];
        for (let menuRoute of routes) {
            if (menuRoute.children && menuRoute.children?.length>0){
                const res = getCacheName(menuRoute.children)
                cacheComponentNames.push(...res.cacheComponentNames)
                noCacheComponentNames.push(...res.noCacheComponentNames)
            }else if (menuRoute.name) {
                if (!menuRoute.meta?.ignoreKeepAlive){
                    noCacheComponentNames.push(menuRoute.name)
                }else {
                    cacheComponentNames.push(menuRoute.name)
                }
            }
        }
        return {
            cacheComponentNames,
            noCacheComponentNames
        }
    }

    return getCacheName(portalRoutes.concat(ConsoleRoutes))
}


export const useCacheStore = defineStore({
    id: 'cache',
    state: ():CacheState => (getCacheMenuComponentNames()),
    getters: {
        getCacheName():RouteRecordName[]{
            return this.cacheComponentNames || getCacheMenuComponentNames().cacheComponentNames;
        },
        getNoCacheName():RouteRecordName[]{
            return this.noCacheComponentNames || getCacheMenuComponentNames().noCacheComponentNames;
        },
    }
})


// Need to be used outside the setup
export function useMenuStoreWithOut() {
    return useCacheStore(store);
}
